<template>
  <div class="flex h-full">
    <!-- 主内容区域 -->
    <div class="flex-1 flex flex-col">

      <!-- 左右分栏内容 -->
      <div class="flex-1 flex overflow-hidden">
        <!-- 左侧：上传区域 (400px) -->
        <div class="w-[400px] border-r border-gray-200 flex flex-col flex-shrink-0">
          <div class="p-6 flex-1 overflow-y-auto">
            <ImageUpload
              ref="imageUploadRef"
              v-model:selectedImages="selectedImages"
              :isAnalyzing="isAnalyzing"
              :currentAnalyzingIndex="currentAnalyzingIndex"
              @analyze="analyzeImages" />
          </div>
        </div>

        <!-- 右侧：分析结果 (剩余空间) -->
        <div class="flex-1 flex flex-col">
          <div class="p-6 flex-1 overflow-y-auto">
            <AnalysisResults
              :analysisResults="analysisResults"
              :isLoading="isAnalyzing"
              :loadingCount="selectedImages.length"
              @export-results="exportResults"
              @download-report="downloadReport"
              @analyze-again="analyzeAgain" />
          </div>
        </div>
      </div>
    </div>

    <!-- 模型设置侧边栏 -->
    <ModelSettingsPanel
      :selectedModel="modelSettings.selectedModel"
      :parameters="modelSettings.parameters"
      :availableModels="modelSettings.availableModels"
      @update:selectedModel="updateSelectedModel"
      @update:parameters="updateParameters"
      @reset="resetModelSettings"
      @save="saveModelSettings"
      @test="testModelSettings" />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import ModelSettingsPanel from "@/components/ModelSettingsPanel.vue";
import ImageUpload from "@/components/ImageUpload.vue";
import AnalysisResults from "@/components/AnalysisResults.vue";

const selectedImages = ref([]);
const isAnalyzing = ref(false);
const currentAnalyzingIndex = ref(0);
const analysisResults = ref([]);
const imageUploadRef = ref(null);
const modelSettings = ref({
  selectedModel: "yolov8",
  parameters: {
    confidenceThreshold: 0.5,
    nmsThreshold: 0.4,
    inputSize: "608",
    batchSize: "4",
    enableGPU: true,
    enablePreprocessing: true,
    enablePostprocessing: true,
  },
  availableModels: [
    {
      id: "yolov8",
      name: "YOLOv8",
      description: "最新的YOLO模型，平衡精度和速度",
      icon: "🚀",
      accuracy: 95,
      speed: "快",
      size: "6.2MB",
    },
    {
      id: "yolov5",
      name: "YOLOv5",
      description: "经典YOLO模型，稳定可靠",
      icon: "⚡",
      accuracy: 92,
      speed: "很快",
      size: "4.1MB",
    },
    {
      id: "efficientdet",
      name: "EfficientDet",
      description: "高效检测模型，适合移动端",
      icon: "📱",
      accuracy: 90,
      speed: "极快",
      size: "2.8MB",
    },
    {
      id: "fasterrcnn",
      name: "Faster R-CNN",
      description: "高精度检测模型，适合高要求场景",
      icon: "🎯",
      accuracy: 98,
      speed: "慢",
      size: "15.6MB",
    },
  ],
});
const analyzeImages = async () => {
  if (selectedImages.value.length === 0) return;

  isAnalyzing.value = true;
  analysisResults.value = [];

  try {
    for (let i = 0; i < selectedImages.value.length; i++) {
      currentAnalyzingIndex.value = i;

      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 模拟分析结果
      const result = {
        originalImage: selectedImages.value[i].url,
        status: Math.random() > 0.5 ? "smooth" : Math.random() > 0.5 ? "slow" : "congested",
        confidence: Math.floor(Math.random() * 30) + 70,
        analysisTime: Math.floor(Math.random() * 500) + 200,
      };

      analysisResults.value.push(result);
      
      // 标记当前图片为已上传
      if (imageUploadRef.value) {
        imageUploadRef.value.markAsUploaded(selectedImages.value[i].name);
      }
    }
  } catch (error) {
    console.error("批量分析失败:", error);
    alert("批量分析失败，请重试");
  } finally {
    isAnalyzing.value = false;
    currentAnalyzingIndex.value = 0;
  }
};

const getStatusText = (status) => {
  const statusMap = {
    smooth: "畅通",
    slow: "缓行",
    congested: "拥堵",
  };
  return statusMap[status] || "未知";
};

const getStatusCount = (status) => {
  return analysisResults.value.filter((result) => result.status === status).length;
};

const exportResults = () => {
  const csvContent = generateCSV();
  downloadFile(csvContent, "analysis_results.csv", "text/csv");
};

const downloadReport = () => {
  const reportContent = generateReport();
  downloadFile(reportContent, "analysis_report.txt", "text/plain");
};

const analyzeAgain = () => {
  analysisResults.value = [];
  analyzeImages();
};

const generateCSV = () => {
  const headers = ["图片名称", "道路状态", "置信度", "分析时间(ms)"];
  const rows = analysisResults.value.map((result, index) => [
    `图片${index + 1}`,
    getStatusText(result.status),
    result.confidence,
    result.analysisTime,
  ]);

  return [headers, ...rows].map((row) => row.join(",")).join("\n");
};

const generateReport = () => {
  const total = analysisResults.value.length;
  const smooth = getStatusCount("smooth");
  const slow = getStatusCount("slow");
  const congested = getStatusCount("congested");

  return `路况分析报告
===============

总图片数: ${total}
畅通: ${smooth} (${((smooth / total) * 100).toFixed(1)}%)
缓行: ${slow} (${((slow / total) * 100).toFixed(1)}%)
拥堵: ${congested} (${((congested / total) * 100).toFixed(1)}%)

详细结果:
${analysisResults.value
  .map((result, index) => `图片${index + 1}: ${getStatusText(result.status)} (置信度: ${result.confidence}%)`)
  .join("\n")}`;
};

const downloadFile = (content, filename, mimeType) => {
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  link.click();
  URL.revokeObjectURL(url);
};

// 模型设置相关方法
const updateSelectedModel = (modelId) => {
  modelSettings.value.selectedModel = modelId;
};

const updateParameters = (parameters) => {
  modelSettings.value.parameters = { ...modelSettings.value.parameters, ...parameters };
};

const resetModelSettings = () => {
  modelSettings.value.selectedModel = "yolov8";
  modelSettings.value.parameters = {
    confidenceThreshold: 0.5,
    nmsThreshold: 0.4,
    inputSize: "608",
    batchSize: "4",
    enableGPU: true,
    enablePreprocessing: true,
    enablePostprocessing: true,
  };
};

const saveModelSettings = () => {
  const settings = {
    model: modelSettings.value.selectedModel,
    parameters: modelSettings.value.parameters,
  };
  localStorage.setItem("modelSettings", JSON.stringify(settings));
  console.log("保存设置:", settings);
  alert("设置已保存！");
};

const testModelSettings = () => {
  console.log("测试设置:", {
    model: modelSettings.value.selectedModel,
    parameters: modelSettings.value.parameters,
  });
  alert("设置测试完成！");
};


onMounted(() => {
  // 加载保存的设置
  const savedSettings = localStorage.getItem("modelSettings");
  if (savedSettings) {
    try {
      const settings = JSON.parse(savedSettings);
      modelSettings.value.selectedModel = settings.model || "yolov8";
      modelSettings.value.parameters = { ...modelSettings.value.parameters, ...settings.parameters };
    } catch (error) {
      console.error("加载设置失败:", error);
    }
  }
});
</script>
